#!/usr/bin/env php
<?php
require_once('bootstrap.php');
require_once('bulldoc/output_generator.php');
require_once('bulldoc/chm_generator.php');


class docgenBuilder extends bookLoader
{
  
//---------------------------------------------------
  private function buildBook($key)
  {
    if (!isset($this->books[$key])) {
      $this->createBook($key);
      echo 'New book created';
    } else {
      if (file_exists(bulldocGetIndexCacheFileName($key))) unlink (bulldocGetIndexCacheFileName($key));
      $render=$this->getBook($key)->getBookRenderer();
      $render->setMode('static');
      $generator= new outputGenerator($render,$this->getBook($key)->getBookDest());
      $generator->build();
      if ($this->getBook($key)->needChm()) {
        $this->buildCHMToc($key);
        $this->buildCHMIndex($key);
      }
    }
  }
//---------------------------------------------------
  private function createBook($key)
  {
    $bookDir=colesoApplication::getConfigVal('/bulldoc/workshopDir')."source/$key/";
    mkdir ($bookDir,0666);
    mkdir ($bookDir.'pages',0666);
    file_put_contents($bookDir.'toc.yml','');
    file_put_contents($bookDir.'book_data.yml',"title: $key\nauthor: Incognito\ncopyright: Me, 2008\nsite: www.mysite.ru");
    
    $bookshelfFile=colesoApplication::getConfigVal('/system/docRoot').'config/bookshelf.yml';
    file_put_contents($bookshelfFile,"\n$key:",FILE_APPEND);
  }
//---------------------------------------------------
  private function buildCHMToc($key)
  {
    $tocFile=$this->getBook($key)->getTocFileName();
    $chmBuilder=new buildCHMToc($tocFile,$key);
    list($toc,$proj)=$chmBuilder->buildTOC();
    $outputPath=rtrim($this->getBook($key)->getBookDest(),'\\/').'/';
    file_put_contents($outputPath.$key.'.hhc',$toc);
    file_put_contents($outputPath.$key.'.hhp',$proj);
    echo "\nchm structure built\n";
  }
  
//---------------------------------------------------
  private function buildCHMIndex($key)
  {
    $myBook=$this->getBook($key);
    $sourcePath=$myBook->getBookRenderer()->getSourcePath();
    $toc=$myBook->getBookRenderer()->getToc();
    $indexBuilder=new IndexBuilder($sourcePath,$toc);
    $myIndexRender=new IndexRender($indexBuilder,$key,null);
    $content=$myIndexRender->renderCHMIndex();

    $outputPath=rtrim($this->getBook($key)->getBookDest(),'\\/').'/';
    file_put_contents($outputPath.$key.'.hhk',$content);
    echo "chm index built\n";
  }
//---------------------------------------------------
  public function run()
  {
    global $argc,$argv;
    if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
      require (colesoApplication::getConfigVal('/bulldoc/systemTemplates').'help.tpl.phtml');
    } else {
      $key=$argv[1];
      $this->buildBook($key);
    }
  }
}

$builder=new docgenBuilder();
$builder->run();
?>